""" DigitalICS: mobile data collection tool to complete surveys with integrated multimedia

    Copyright (C) 2009. Yael Schwartzman  

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>
    
    Contact information: Yael Schwartzman -  yaelsf@gmail.com
    """
    
from api.form import Form
from api.prompt import Prompt
from api.constants import Constants
from api.fexplorer import FExplorer  
from api.controller import Controller 
from api.db import db
import view.camui as camui
import e32,appuifw,os,time
from api.logger import logger
from api.pickler import Pickler
import key_codes
import graphics

from api.lang import Lang,Properties
p = Properties()
l = Lang(p.LANGUAGE)


class FormMView:
    """ Manages the view for each form, input type, prompt, etc. """

    def __init__(self,form = None):
        self.app_lock = e32.Ao_lock()
        self.fexplorer = FExplorer()
        self.parent = None
        self.constants = Constants()
        self.pickler = Pickler()
        self.id_type = "INTEGER"
        
        if form is None:
            self.form = None
            self._do_front_page()
        else:
            self.form = form
            self.page = self.constants.FORM
            self.controller = Controller(form)
            self._do_view()
        
        self.app_lock.wait()


    def _do_front_page(self):
        self.page = self.constants.FRONT

        appuifw.app.set_tabs([u''],None)
        canvas = appuifw.Canvas(event_callback = None, redraw_callback=None)

        appuifw.app.screen = 'normal' 
        appuifw.app.body = canvas
        appuifw.app.exit_key_handler=self.quit
        appuifw.app.title = unicode(l.WELCOME)
                
        appuifw.app.menu = self._get_menu("front")
         

    def _get_menu(self,type):
            
        menu = [(unicode(l.NEW), self.new_form),
        (unicode(l.OPEN), self.load_form)]
        
        if type == 'form':
            menu.extend([(unicode(l.SAVE), self.save_form),
                         (unicode(l.TAKE_PICTURE), self.take_picture), 
                         (unicode(l.RECORD_AUDIO), self.record_audio)])
        
        menu.extend([(unicode(l.COMMENTS), self.do_feedback_audio),
                     (unicode(l.DELETE),self.delete),
                     (unicode(l.EXIT), self.quit)
                     ])
                                
        return menu
        
        
    def do_feedback(self,origin = "voluntary",inspector = None):
        """ feedback for developers or staff"""
        if inspector is None:
            inspector = camui.query(unicode(l.INSPECTOR), "number",audio=l.A_INSPECTOR)
        if self.form is not None:
            self.form.save_form()
        self.record_audio(inspector,origin = origin)
        
    def do_feedback_audio(self):
        if self.form is not None:
            self.form.save_form()
        self.record_audio(inspector = 1, origin = "menu")
    
    def do_feedback_pic(self):
        if self.form is not None:
            self.form.save_form()
        self.take_picture(inspector = 1,origin = "menu")
    
    def delete(self):
        password = 1981
        user_pass = camui.query(unicode(l.PASSWORD),"number")
        if user_pass == password:
            if camui.query(unicode(l.CONFIRM_ERASE),"query"):
                self.fexplorer.delete_data()
            camui.note(unicode(l.DATA_ERASED),"conf")
        else:
            camui.note(unicode(l.INCORRECT_PASSWORD),"error")
    
    def _do_view(self,index = 0):
        """ does the main form view"""
        appuifw.app.orientation= 'portrait'
        appuifw.app.screen='normal' #(only softkeys visible)
        #set the exit function
        appuifw.app.exit_key_handler=self.quit

        #title 
        appuifw.app.title = "%s: %s" % (self.form.get_id(),self.form.get_name())  

        # create your content list of your listbox including the icons to be used for each entry
        main_menu = self.form.get_ids_and_values() 
        
        self.lb = appuifw.Listbox(main_menu,self._lb_callback)
        # create an instance of appuifw.Listbox(), include the content list "entries" and the callback function "shout"
        # and set the instance of Listbox now as the application body
        appuifw.app.body = self.lb
        appuifw.app.body.set_list(main_menu,index)    
        appuifw.app.menu =  self._get_menu("form")
                    
        self._set_tabs()
    
    def _set_tabs(self):
        #if this [form has multimedia or recommendations, show tabs on top to review them
        if self.form.has_no_identification():
            tab_list = [u'%s'%self.form.id]
        else:
            tab_list = [u'%s'%self.form.id,u'recomendaciones.txt']
        path = self.get_media_path(query = False)
        if path:
            tab_list.extend(self.form.get_audio_and_pictures(path))
        
        appuifw.app.set_tabs([u'%s'%file for file in tab_list],self._media_tabs_callback)
        
    def _media_tabs_callback(self,index):
        appuifw.app.activate_tab(index)
        
        if self.page == self.constants.FORM:
            if index == 0:
                appuifw.app.body = self.lb
                self._do_view()
            else:
                e32.ao_sleep(.3)
                path = self.get_media_path(query = False)
                if self.form.has_no_identification():
                    tab_list = [u'%s'%self.form.id]
                else:
                    tab_list = [u'%s'%self.form.id,u'recomendaciones.txt']
                tab_list.extend(self.form.get_audio_and_pictures(path))
                file = tab_list[index]
                if file.endswith(".txt"):
                    rec = self._get_recommendations()
                    text_body = appuifw.Text(unicode(rec,"latin-1"))
                    text_body.font = u'LatinBold80'
                    appuifw.app.body = text_body 
                    appuifw.app.title = u"Recomendaciones"
            
                if file.endswith(".jpg"):
                    appuifw.app.body = camui.show_picture("%s\\pics"%path,file)
                elif file.endswith(".amr") or file.endswith('.wav'):
                    appuifw.app.body = camui.show_audio("%s\\audio"%path,file)
        else:
            self._do_front_page()
    
    def take_picture(self,inspector = None, section = None,origin = "voluntary"):
        filename ="foto_%s.jpg" % self._create_file_name(inspector,section,origin)
        if inspector is not None:
            #doing feedback
            taken = camui.take_picture(filename,self.fexplorer.get_feedback_folder())
            
        else:
            media_path = self.get_media_path()
            if media_path:  
                camui.take_picture(filename,'%s\\pics' % media_path)
            else:
               camui.note(l.CODES_FIRST)
               logger.log_error("Please enter Community and Producer first")

        if self.page == self.constants.FRONT:
            self._do_front_page()
        else:
            self._do_view()
    
    
    def record_audio(self,inspector = None,section = None,origin = "voluntary"):
        filename = "audio_%s.amr" % self._create_file_name(inspector,section,origin)
        if inspector is not None:
            #doing feedback
            taken = camui.record(filename,self.fexplorer.get_feedback_folder())
    
        else:
            media_path = self.get_media_path() 
            if media_path:
                recorded = camui.record(filename,'%s\\audio' % media_path,audio="record_audio")
            else:
                logger.log_error("incorrect media path for take audio feedback %s" %filename)
    
    
        if self.page == self.constants.FRONT:
            self._do_front_page()
        else:
            self._do_view()
    
    def _create_file_name(self,inspector,section,origin):
        if inspector is not None:
            return "insp_%s" % inspector + "_%s_"%origin + time.strftime("%a_%d_%b_%Y_%H_%M_%S", time.gmtime())
        if section is not None: 
            sect  = "%s_" % section
        else:  
            sect = "" 
        return sect + time.strftime("%a_%d_%b_%Y_%H_%M_%S", time.gmtime())


    def _get_community(self):    
        appuifw.app.set_tabs([u''],None)
        appuifw.app.title = unicode(l.ORGANIZATION)
        communities = self.fexplorer.get_id_list()
        index = camui.selection_list(choices = [u'%s'%c for c in communities], search_field=1,audio = "organization") 
        #if index == (len(communities)-1):
        #    return (self.prompt_for_new(l.ORGANIZATION,communities),True)
        #else:
        try:
            return  communities[index]
        except: 
            return False
    
    def _get_municipio(self,args):    
        commty = args[0]
        appuifw.app.title =u"Municipio"
        muns = self.fexplorer.get_id_list([commty])
        index = camui.selection_list(choices = muns , search_field=1,audio = "municipio") 
        try:
            return  muns[index]
        except: 
            return False
            
    def _get_localidad(self,args):    
        commty,munic = args[0],args[1]
        appuifw.app.title =u"Localidad:"
        locs = self.fexplorer.get_id_list([commty,munic])
        index = camui.selection_list(choices = locs, search_field=1,audio = "localidad") 
        try:
            return locs[index]
        except: 
            return False
    
    def _get_producer(self,args):
        if self.id_type == "LIST":
            appuifw.app.set_tabs([u''],None)
            appuifw.app.title =unicode(l.PRODUCER)
            producers = self.fexplorer.get_id_list(args)
            #producers = self.pickler.get_producer_names(community)
            index = camui.selection_list(choices = [u'%s'% p for p in producers], search_field=1, audio = "producer") 
            try: 
                return producers[index]
            except:
                return False
            
        else:
            commty,munic,loc = args[0],args[1],args[2]
            appuifw.app.title =u"%s"%l.PRODUCER
            producers = self.fexplorer.get_id_list(args = [commty,munic,loc])
            index = camui.selection_list(choices = producers, search_field=0, audio = "productor") 
            try: 
                return producers[index]
            except:
                return False
            
    def prompt_for_new(self,name,existing_id_list ):
        id = camui.query(u"%s"%name,"number",audio = name)
        id = "%s"% id
        if id in existing_id_list :
            if camui.query(unicode(l.EXISTING_ID),"query",l.A_EXISTING_ID):
                return self.prompt_for_new(name,existing_id_list )
            else:
                return False
        else:
            return id
    
    def _get_form_path(self,only_producer = False):
        old_title = appuifw.app.title
        community = self._get_community()
        if self.id_type == 'INTEGER':
            munic = self._get_municipio([community])
            loc=self._get_localidad([community,munic])
            producer = self._get_producer([community,munic,loc])
            return (community,munic,loc,producer)
        else:
            producer = self._get_producer(community)
            return (community,producer)
        appuifw.app.title = old_title
        
    def load_form(self):
        self.page = self.constants.FORM
        if self.id_type == 'LIST':
            community,producer = self._get_form_path()
        else:
            community,munic,loc,producer = self._get_form_path()
        if community == False:
            return False
        else:
            exec("from forms.%(mf)s import %(mf)s" % ({'mf':p.MASTER_FORM}))
            function = eval(p.MASTER_FORM)
            if self.id_type == 'LIST':
                self.form = function(community,producer)
            else:
                self.form = function(community,munic,loc,producer)
            if self.form.load_form():     
                camui.note(unicode(l.LOADING_SUCCESSFUL), "conf",l.A_LOADING_SUCCESSFUL)
            else:
                camui.note(unicode(l.LOADING_UNSUCCESSFUL), "error", l.A_LOADING_UNSUCCESSFUL)
                return False
        
            self.form.update_data_value(l.PRODUCER,producer)
            self.form.update_data_value(l.ORGANIZATION,community)
            self._do_view()
            self.controller = Controller(self.form)
            appuifw.app.title = "%s: %s" % (self.form.get_id(),self.form.get_name())  
            self.update_form_view()
            return True
        
    def save_form(self):
        if self.form.has_no_identification():
            if self.form.has_everything_but_producer():
                if self.id_type == 'LIST':
                    community,producer = self._get_form_path(only_producer = True)
                else:
                    community,munic,loc,producer = self._get_form_path(only_producer = True)
            else:
                if self.id_type == 'LIST':
                    community,producer = self._get_form_path()
                else:
                    community,munic,loc,producer = self._get_form_path(only_producer = True)
            if community != False:
                self.form.set_community_id(community)
                self.form.set_producer_id(producer)
                if self.id_type == 'INTEGER':
                    self.form.set_municipio_id(munic)
                    self.form.set_localidad_id(loc)
                    
        if self.form.save_form():
            camui.note(unicode(l.SAVING_SUCCESSFUL), "conf", l.A_SAVING_SUCCESSFUL)
        else:
            camui.note(unicode(l.SAVING_UNSUCCESSFUL), "error",l.A_SAVING_UNSUCCESSFUL)    
    
        self._set_tabs()   
        
    
    
    def new_form(self):
        if self.page == self.constants.FORM:
            if camui.query(unicode(l.SAVE_QUERY),"query" ,audio = l.A_SAVE_QUERY):
                self.form.save_form()
        
        self.page = self.constants.FORM
        exec("from forms.%(mf)s import %(mf)s" % ({'mf':p.MASTER_FORM}))
        master_form =eval(p.MASTER_FORM) 
        self.form = master_form()
        self.controller = Controller(self.form)
        self._do_view()
        self.form.clear_values()
        self.form.update_with_common_ids()
        self.controller.set_prompt_id(-1)
        self.show_next_prompt()
        
    def complete_form(self, prompt_id = -1):
        self.controller.set_prompt_id(prompt_id)
        self.show_next_prompt()
        
    def _lb_callback(self):
        
        item = self.lb.current()
        item -=1
        self.complete_form(prompt_id = item)
        
    def quit(self):
        # if in front page then ask the user if they want to exit
        # if on main form go to front page
        # if on child form go to main form
        
        if self.page == self.constants.FRONT:
            if camui.query(unicode(l.EXIT_QUERY),'query',l.A_EXIT_QUERY):
                self.app_lock.signal()
                appuifw.app.set_exit()
        else:
            if self.form is not None:
                if camui.query(unicode(l.SAVE_QUERY),'query',l.A_SAVE_QUERY):
                    self.save_form()
            if self.parent is not None:
                if camui.query(unicode(l.GO_BACK_QUERY),"query",l.A_GO_BACK_QUERY):
                    return self.revert_to_parent()
                else: return self.update_form_view()
            else:    
                
                return self._do_front_page()
            
           
    def show_next_prompt(self):         
        prompt = self.controller.get_next_prompt()
        # HACK to save the form before we go into the media in case something breaks so 
        # we don't lose the info
        if not prompt: 
            if not self.parent is None:
                if camui.query(unicode(l.SAVE_GO_BACK_QUERY),"query",l.A_SAVE_GO_BACK_QUERY):
                    self.save_and_revert_to_parent()
                else:
                    self.update_form_view(with_title = True)
        else:
            index = self.form.get_prompt_index(prompt)
            self.update_form_list(index)
            got_input = self.show_prompt(prompt) 
            if got_input:
                # so that it does not continue prompting for the form
                if not (prompt.get_input_type() == self.constants.FORM and prompt.get_id() == self.form.get_id()):
                    if not self.form.get_id()== "Section5": 
                        self.update_form_view(index,with_title = True)
                        self.show_next_prompt()
            else:
                self.update_form_view(index,with_title = True)
         
                
            
    def show_prev_prompt(self):
        prompt = self.controller.get_prev_prompt()
        self.update_form_view()
        if not prompt: 
            if not self.parent == None:
                
                if camui.query(unicode(l.SAVE_GO_BACK_QUERY),"query",l.A_SAVE_GO_BACK_QUERY):
                    self.save_and_revert_to_parent()
        else:
            self.show_prompt(prompt)
        
    
    def revert_to_parent(self):
        """ revert to parent or to master form if no parent"""
    
        if self.parent:
            # if the child form has been identified pass this information to the parent
            self.page = self.constants.FORM
            if self.parent.has_no_identification() and not self.form.has_no_identification():
                self.parent.set_community_id(self.form.get_community_id())
                self.parent.set_producer_id(self.form.get_producer_id())
                
            data = self.parent_prompt.get_data()
            form_id = self.form.get_id()
            
            self.form = self.parent            
            self.form.update_data_value(data,l.COMPLETED)
        else:
            self._do_front_page()
            print "no parent for form %s prod % comm %s" % (
                                        self.form.get_id(),
                                        self.form.get_producer_id(),
                                        self.fomr.get_community_id())
            
            exec("from forms.%(mf)s import %(mf)s" % ({'mf':p.MASTER_FORM}))
            master_form = eval(p.MASTER_FORM)
            self.form = master_form()
            
        self.parent = None
        self.parent_prompt = None
        index = self.form.get_index_for_prompt_id(form_id)
        self.controller = Controller(self.form,prompt_id = index)
        self.update_form_view(index = index, with_title = True)

    def save_and_revert_to_parent(self):
        self.form.update_data_value("ts2",time.strftime("%a %d/%b/%Y %H:%M:%S", time.gmtime()))
        self.save_form()
        self.revert_to_parent()
    
    
    def show_prompt(self,prompt):
        input_type = prompt.get_input_type()
        repeat = self._get_repeat(prompt)
        if repeat is not None:
            id = prompt.get_id()
            existing = self.form.get_existing_repeated_prompts(id)
            if repeat < existing:
                self.form.remove_prompts(id,existing - repeat)
            else:
                repeat_vars= range(existing+1, len(repeat)+1)
                for i in repeat_vars:
                    ans = self._handle_new_prompt(prompt,i)
                    if ans == False:
                        return ans
                return True
        else:
            return self._handle_input_types(input_type,prompt)
    
    def _get_repeat(self,prompt):
        repeat = prompt.get_repeat() 
        if repeat is None: return None
        type_repeat = type(repeat)
        if type_repeat == int:
            return range(1,repeat+1)
        elif type_repeat == list or type_repeat == tuple:
            return repeat
        else:
            value = self.form.get_data_value(id = repeat) 
            if type(value) == int :
                return range(1,value+1)
            else:
                return value   
            
    def _handle_input_types(self,input_type,prompt): 
        if input_type == self.constants.DB_INPUT:
            return self._handle_db_input(prompt)
        if input_type == self.constants.INPUT:
            return self._handle_input(prompt)
        elif input_type == self.constants.SELECT1:
            return self._handle_select1(prompt) 
        elif input_type == self.constants.SELECT:
            return self._handle_select(prompt)  
        elif input_type == self.constants.TEXTAREA:
            return self._handle_textarea(prompt) 
        elif input_type == self.constants.AUDIO:
            return self._handle_audio(prompt) 
        elif input_type == self.constants.PHOTO:
            return self._handle_photo(prompt) 
        elif input_type == self.constants.FORM: 
            return self._handle_form(prompt)
        elif input_type == self.constants.FEEDBACK: 
            return self._handle_feedback(prompt)
   
    def _get_recommendations(self):
        if self.id_type == 'INTEGER':
            results = self.pickler.get_recommendation(community = self.form.get_community_id(),
                                                      municipio = self.form.get_municipio_id(),
                                                      localidad = self.form.get_localidad_id(),
                                                      producer = self.form.get_producer_id())
        else:
            results = self.pickler.get_recommendation(community = self.form.get_community_id(),
                                                      producer = self.form.get_producer_id())
        return results
    
    def _handle_db_input(self,prompt):
        #STUB
        #CLAVE_ORG = 'E0374540001067' 
        
        if prompt.data == l.PRODUCER:
            results = self.pickler.get_producer_names(self.form.get_community_id())
        elif prompt.data == l.ORGANIZATION:
            results = self.pickler.get_communities()
        elif prompt.data == 'recomendaciones':
            results = self._get_recommendations()
        else:
            db_method = eval("self.pickler" + prompt.get_method())
            results = db_method()
            
        if prompt.return_type==self.constants.SELECT1:
            prompt.options = [unicode("%s"%result,"latin-1") for result in results]
            self._handle_select1(prompt)
        else:
            text_body = appuifw.Text(unicode(results))
            text_body.font = u'LatinBold80'
            appuifw.app.body = text_body 
            appuifw.app.title = u"%s" % prompt.get_label()
            
        
    def _handle_feedback(self,prompt):        
        audio = prompt.get_audio()
        label = prompt.get_label()
        id = prompt.get_id()
        if camui.query(u'%s'% label,"query", audio = audio ): 
            self.do_feedback(inspector = self.form.get_inspector(),origin = id)
            return True
        else:
            return False
        
    def _handle_new_prompt(self,prompt,repeat):
        #TODO - Right now this is specific to num_parcels
        id = prompt.get_id()
        repeat_var = repeat
        
        label = self.form.get_repeated_label(prompt.get_label(),repeat)
        label =  label.replace("#REPEAT_VAR", "%s" % repeat_var)
        
        new_id = self.form.get_repeated_id(id,repeat)
        data = self.form.get_repeated_data(prompt.get_data(),repeat)
        
        output = prompt.output.replace("#REPEAT_VAR", "%s" % repeat_var)
        media_file =  prompt.get_media_file()
        if media_file is not None:
            media_file = "%s_%s"% (repeat,media_file) 
            
        new_prompt = Prompt(id = new_id,
                            label = label,
                            data = data,
                            media_file = media_file,
                            output = output,
                            input_type = prompt.input_type,
                            return_type = prompt.return_type,
                            options = prompt.options,
                            relevance = prompt.relevance,
                            audio = prompt.audio,
                            module = prompt.module)
    
        if not self.form.has_prompt(new_id):
            self.form.add_repeated_prompt(id,repeat,new_prompt)
            self.form.add_data(data)
            
        return True 
        
    def _handle_input(self,prompt):
        input_type = prompt.get_input_type()
        return_type = prompt.get_return_type()
        default = prompt.get_default()
        label = prompt.get_label()
        data = prompt.get_data()
        default_value = self.form.get_data_value(data_name = data)
        
        if default_value  is None and default:
            default_value = default
        if type(default_value) == str:
            default_value = default_value.strip()
        audio = prompt.get_audio()
        
        if return_type == self.constants.RETURN_INTEGER:
            #Handle integer
            ans = self._handle_integer_entry(data,label,default_value,audio) 
        
        elif return_type == self.constants.RETURN_FLOAT:
            #Handle floats
            if default_value == None or default_value == "" : 
                ans = camui.query(u"%s" % label, "float",audio = audio) 
            else:
                ans = camui.query(u"%s" % label, "float",def_value = float(default_value), audio=audio)

        elif return_type == self.constants.RETURN_STRING:
            #Handle strings 
            ans = self._handle_string_entry(data,label,def_value = default_value , audio =  audio) 
        
        elif return_type == self.constants.RETURN_DATE:
            
            if  default_value == None or default_value ==  "": 
                default_value = time.time()
    
            ans = camui.query(u"%s" % label, "date",def_value = float(default_value), audio = audio)

        elif return_type == self.constants.RETURN_BOOLEAN:    
            #Handle boolean
            ans = camui.boolean(title = u"%s" % label,audio=audio, def_value = default_value) 
        
        if ans == None: 
            ans = default_value
            got_input = False
        else:
            got_input = True
        self.form.update_data_value(data,ans)
        return got_input
    
    def _handle_string_entry(self,data,label,def_value,audio):
        if not def_value == None: 
            ans = camui.query(u"%s" % label, "text",def_value = u'%s'% def_value, audio=audio)
        else: 
            ans = camui.query(u"%s" % label, "text", audio=audio)
         
        return ans
    
    def _handle_integer_entry(self,data,label,def_value,audio):
        """ to save the community, inspector and producer id as
            instance variables"""
        try:
            def_value = int(def_value)
            ans = camui.query(u"%s" % label, "number",audio=audio,def_value = int(def_value))
        except:
            ans = camui.query(u"%s" % label, "number", audio=audio)            
                
        if data == l.PRODUCER and ans: 
            self.form.set_producer_id(ans)
        elif data == l.ORGANIZATION and ans: 
            self.form.set_community_id(ans)
        elif data == l.MUNICIPIO and ans:
            self.form.set_municipio_id(ans)
        elif data == l.LOCALIDAD and ans:
            self.form.set_localidad_id(ans)
        return ans
        
    def _handle_select1(self,prompt):
        options = [u"%s"% value for value in prompt.get_options()]
        
        data = prompt.get_data()
        label = prompt.get_label()
        audio = prompt.get_audio()
        def_value =self.form.get_data_rep(prompt= prompt)
        index = camui.selection_list(choices = options, search_field=1,title = label, audio=audio, def_value = def_value)
        
        if index is None:
            return False
         
        else:
            if data == l.ORGANIZATION or data == l.PRODUCER:
                ans = options[index]
                if data == l.PRODUCER and ans: 
                    self.form.set_producer_id(ans)
                elif data == l.ORGANIZATION and ans: 
                    self.form.set_community_id(ans)
                
                #print "%s form.community %s form.producer"% (self.form.get_community_id(),self.form.get_producer_id())
             
            else:
                if type(index) == tuple:
                    ans = index[0]
                elif type(index) == str:
                    ans = index
                elif type(index) == int:
                    ans = options[index]
    
            self.form.update_data_value(data,ans)
            return True
        
    def _handle_select(self,prompt):
        options = [u"%s"% value for value in prompt.get_options()]
        chosen = [] 
        data = prompt.get_data()
        label = prompt.get_label()
        audio = prompt.get_audio()
        def_value =self.form.get_data_rep(prompt = prompt)
        
        index = camui.multi_selection_list(options , style='checkbox', search_field=0,title = label, audio=audio, def_value = def_value)
        if index is None or not index:
            return False
        else:

            self.form.update_data_value(data,index)
            return True

    def _handle_textarea(self,prompt):
        #TODO do text area
        camui.note(u"TextArea", "info")
        
    def _handle_audio(self,prompt):
        if self.form is not None:
            self.form.save_form()
        id = self.form.get_id()
        filename = "%s_%s" % (id,prompt.get_media_file())
        title = prompt.get_label()
        audio = prompt.get_audio()                       
        media_path = self.get_media_path()
        if media_path:
            recorded = camui.record(filename = filename, title = title,media_path = '%s\\audio' % media_path, audio = audio) 
            if recorded:
                self.form.update_data_value(prompt.get_data(),l.AUDIO_RECORDED)
            else:
                self.form.update_data_value(prompt.get_data(),l.AUDIO_NOT_RECORDED)
                
            self._do_view(self.form.get_prompt_index(prompt))
            return True
        else:
            logger.log_error("incorrect media path for take picture feedback %s" %filename)
            self._do_view(self.form.get_prompt_index(prompt))
            return False
         
    
    def get_media_path(self,query = True):
        """ this is where the picture or recording gets saved"""      
        
        if self.id_type == 'LIST':
            commty,prod = self.form.get_media_path()
            if commty  == 'None' or prod  == 'None':
                if query:     
                    commty,prod = self._get_form_path() 
                else: return False        
            else:
                media_path = self.form.make_media_path(commty,prod)
                return media_path
        else:
            commty,muni,loc,prod = self.form.get_media_path()
            if commty  == 'None' or prod  == 'None' or muni == 'None'  or loc == 'None':
                if query:     
                    commty,muni,loc,prod = self._get_form_path() 
                else: return False        
            else:
                media_path = self.form.make_media_path(community = commty,municipio =muni,
                                                       localidad = loc,producer = prod)
                return media_path
                
        
    def _handle_photo(self,prompt):
        id = self.form.get_id()
        filename = "%s_%s" % (id,prompt.get_media_file())
        title = prompt.get_label()
        if self.form is not None:
            self.form.save_form()    
        media_path = self.get_media_path()
        if media_path:
            data = prompt.get_data()
            audio = prompt.get_audio()    
            taken =camui.take_picture(filename = filename, title = title, media_path = '%s\\pics' % media_path, audio = audio ) 
            if taken:
                self.form.update_data_value(data,l.PICTURE_TAKEN)
            else:
                self.form.update_data_value(data,l.PICTURE_NOT_TAKEN)
            
            self._do_view(self.form.get_prompt_index(prompt))
            return True
        else: 
            logger.log_error("incorrect media path in handle photo for prompt %s" % prompt.get_id())
            self._do_view(self.form.get_prompt_index(prompt))
            return False
        
    def _handle_form(self,prompt):
        if camui.query(unicode(l.DO_YOU_WISH_TO_COMPLETE+" "+str(prompt.get_id())+"?"),"query",audio = l.A_DO_YOU_WISH_TO_COMPLETE):
            self.parent_prompt = prompt
            self.parent = self.form        
            function = prompt.get_module()
            community = self.parent.get_community_id()
            producer = self.parent.get_producer_id()
            if self.id_type == 'INTEGER':
                muni = self.parent.get_municipio_id()
                locs = self.parent.get_localidad_id()
                self.form = function(community=community,producer=producer,municipio = muni,localidad=locs)
            else:
                self.form = function(community=community,producer=producer)
            self.form.load_form()
            self.controller = Controller(form = self.form)
            self.update_form_view(with_title = True)
            self.form.update_data_value("ts1",time.strftime("%a %d/%b/%Y %H:%M:%S", time.gmtime()))
            self.complete_form()
            
            return True
        else:
            return False
        
    def update_form_view(self,index = 0,with_title = False):
        
        if self.page == self.constants.FRONT:
            self._do_front_page()
        else:
             
            if self.parent is not None:
                if not appuifw.app.menu.__contains__((unicode(l.MASTER_FORM), self.save_and_revert_to_parent)):
                    appuifw.app.menu.append((unicode(l.MASTER_FORM), self.save_and_revert_to_parent)) 
            
            self.update_form_list(index) 
             
            if with_title:
                appuifw.app.title = "%s: %s" % (self.form.get_id(),self.form.get_name())  
            
            if appuifw.app.exit_key_handler != self.quit:
                appuifw.app.exit_key_handler=self.quit
            
            if not self.form.has_no_identification():
                self._set_tabs()
            
        
    def update_form_list(self,index = 0):
        items = self.form.get_ids_and_values()
        try:
            appuifw.app.body.set_list(items,index)
        except:
            self._do_view()
            appuifw.app.body.set_list(items,index)